package main

import (
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"gitee.com/lihaiping1603/utils/log"
	"gitee.com/lihaiping1603/utils/xhttp"
	"gitee.com/lihaiping1603/utils/xwebsocket"
)

type NodeControl struct {
}

func NewNodeControl() *NodeControl {
	return &NodeControl{}
}

func (nc *NodeControl) OnConnected(ws *xwebsocket.WebsocketSession) error {
	log.Info("session:%s connected", ws.ID())
	return nil
}

func (nc *NodeControl) OnUpgradeError(err error) error {
	return err
}

func (nc *NodeControl) OnHandleTextMessage(ws *xwebsocket.WebsocketSession, data []byte) error {
	log.Info("session:%s data:%s", ws.ID(), data)
	return nil
}

func (nc *NodeControl) OnHandleBinaryMessage(ws *xwebsocket.WebsocketSession, data []byte) error {
	log.Info("session:%s data:%s", ws.ID(), data)
	return nil
}

func (nc *NodeControl) OnClosed(ws *xwebsocket.WebsocketSession) error {
	log.Info("session:%s disconnect", ws.ID())
	return nil
}

func main() {
	node_control := NewNodeControl()

	server := xhttp.NewHttpApiServer()
	server.RegisterHandler("/ws", "", func(w http.ResponseWriter, r *http.Request) {
		xwebsocket.WebsocketUpgrade(w, r, node_control)
	})

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		//wait
		<-c
		server.Stop()
		println("stop server...")
	}()

	if err := server.Start(":9090", "", ""); err != nil {
		println(err.Error())
	}
	return
}
